import 'dart:io';

import 'package:ReadDB/model/enums.dart';
import 'package:ReadDB/model/read_db.dart';
import 'package:ReadDB/model/widget_db_repository.dart';
import 'package:ReadDB/provider_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return PorviderWrapper(
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: SimplePage(title: '读取数据库'),
      ),
    );
  }
}

class SimplePage extends StatefulWidget {
  SimplePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _SimplePageState createState() => _SimplePageState();
}

class _SimplePageState extends State<SimplePage> {
  String _text = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Markdown(data: _text),
        ),
        floatingActionButton: Builder(
          builder: (context) {
            pressAction() {
              print('读取中……');
              readDb(context).then((text) {
                print('写入完毕');
                setState(() {
                  _text = text;
                });
              });
            }

            return FloatingActionButton(
              onPressed: pressAction,
              tooltip: '读取',
              child: Icon(Icons.work),
            );
          },
        ) // This trailing comma makes auto-formatting nicer for build methods.
        );
  }

  Future<String> readDb(BuildContext context) async {
    DbManager _storage = Provider.of<DbManager>(context, listen: false);
    if (_storage == null) return '';
    print('storage: $_storage');

    String text = '# Flutter Unit\n\n';
    WidgetDbRepository _repository = WidgetDbRepository(_storage);

    for (var family in WidgetFamily.values) {
      text += '## ${enumToString(family)}\n\n';
      text += await readWidgets(_repository, family);
    }

    //print(text);
    // 输出到文件
    // final file = File('/Users/bq/Workspace/Test/flutter.md');
    // file.writeAsString(text);
    return text;
  }

  Future<String> readWidgets(
      WidgetDbRepository _repository, WidgetFamily family) async {
    String text = '';
    var widgets = await _repository.loadWidgets(family);
    for (var w in widgets) {
      text += '### ${w.name}\n\n';
      text += '${w.nameCN}。\n\n';
      text += '示例：\n\n';

      var nodes = await _repository.loadNode(w);
      for (var n in nodes) {
        text += '#### ${n.name}\n\n';
        text += '${n.subtitle}\n\n';
        text += '```dart\n${n.code}\n```\n\n';
      }
    }
    return text;
  }

  String enumToString(o) => o.toString().split('.').last;
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
